<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $belongsTo = array('Group');
    var $uses = array("ControlIngreso");


    function login() {
        // Autentificación Magica
//        $usuario=$this->Session->read('Auth.User');
//        if ($usuario) {
//            $u=$this->User->find('first', array('conditions' => array('User.username' => $usuario['username'])));
//                if($u['User']['activo']==0) {
//                $this->Session->setFlash('Adios y nos vemos.');
//                $this->redirect($this->Auth->logout());
//            }
//        }
        if ($this->Auth->user()) {
            $ingreso = array("ControlIngreso"=>array("user_id"=>$this->Auth->user('id'),"hora_ingreso"=>date("Y-m-d H:i:s")));
            $this->ControlIngreso->create();
            $this->ControlIngreso->save($ingreso);
            $this->redirect($this->Auth->redirect());
        }

    }

    function logout() {
        $id=$this->ControlIngreso->query("select id from control_ingresos where user_id=".$this->Auth->user('id')." order by hora_ingreso desc limit 1");    
        $sql="UPDATE control_ingresos set hora_salida='".date("Y-m-d H:i:s")."'
            where id =".$id[0]['control_ingresos']['id'];
        $this->ControlIngreso->query($sql);
        $this->redirect($this->Auth->logout());
    }

    function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('No existe usuario', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->User->create();
            $password1=$this->data['User']['password1'];
            $password2=$this->data['User']['password2'];

            if($password1 ==  $password2) { //contraseña nueva y repetida son iguales
                $this->data['User']['password']=$this->Auth->password($password1);
                if ($this->User->save($this->data)) {
                    $this->Session->setFlash(__('El usuario se creo exitosamente', true));
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('Error al crear usuario, por favor intente de nuevo.', true));
                }
            }
            else {
                $this->Session->setFlash(__('Ingrese correctamente la contraseña nueva.', true));
            }
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('No existe usuario', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                // Verificar si sus permisos de grupo han cambiado
                $oldgroupid = $this->User->field('group_id');
                if ($oldgroupid !== $this->data['User']['group_id']) {
                    $aro = & $this->Acl->Aro;
                    $user = $aro->findByForeignKeyAndModel($this->data['User']['id'], 'User');
                    $group = $aro->findByForeignKeyAndModel($this->data['User']['group_id'], 'Group');

                    // Guardar en la tabla ARO
                    $aro->id = $user['Aro']['id'];
                    $aro->save(array('parent_id' => $group['Aro']['id']));
                }

                $this->Session->setFlash(__('Usuario se modifico exitosamente', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Error al modificar usuario, por favor intente de nuevo.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    function edit_password() {
        $u=$this->Session->read('Auth.User');
        $id = $u['id'];
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Usuario incorrecto', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $password_ant=$this->Auth->password($this->data['User']['password_ant']);
            $password_nuevo=$this->data['User']['password_nuevo'];
            $password_nuevo_rep=$this->data['User']['password_nuevo_rep'];

            if($password_ant == $u['password']) { //contraseña anterior correcta
                if($password_nuevo ==  $password_nuevo_rep) { //contraseña nueva y repetida son iguales
                    $this->data['User']['password']=$this->Auth->password($password_nuevo);
                    if ($this->User->save($this->data)) {
                        // Verificar si sus permisos de grupo han cambiado
                        $this->Session->setFlash(__('La contraseña se ha cambiado correctamente', true));
                        $this->redirect(array('action' => 'index'));
                    } else {
                        $this->Session->setFlash(__('Ocurrio un error al guardar la contraseña.', true));
                    }
                }
                else {
                    $this->Session->setFlash(__('Ingrese correctamente la contraseña nueva.', true));
                }
            }
            else {
                $this->Session->setFlash(__('No coincide contraseña anterior.', true));
            }
//            if ($this->User->save($this->data)) {
//                // Verificar si sus permisos de grupo han cambiado
//                $this->Session->setFlash(__('La contraseña se ha cambiado correctamente', true));
//                $this->redirect(array('action' => 'index'));
//            } else {
//                $this->Session->setFlash(__('Ocurrio un error al guardar la contraseña.', true));
//            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    function edit_password_admin($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Usuario incorrecto', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $password_ant=$this->Auth->password($this->data['User']['password_ant']);
            $password_nuevo=$this->data['User']['password_nuevo'];
            $password_nuevo_rep=$this->data['User']['password_nuevo_rep'];
            $u = $this->User->read(null, $id);
            if($password_ant == $u['User']['password']) { //contraseña anterior correcta
                if($password_nuevo ==  $password_nuevo_rep) { //contraseña nueva y repetida son iguales
                    $this->data['User']['password']=$this->Auth->password($password_nuevo);
                    if ($this->User->save($this->data)) {
                        // Verificar si sus permisos de grupo han cambiado
                        $this->Session->setFlash(__('La contraseña se ha cambiado correctamente', true));
                        $this->redirect(array('action' => 'index'));
                    } else {
                        $this->Session->setFlash(__('Ocurrio un error al guardar la contraseña.', true));
                    }
                }
                else {
                    $this->Session->setFlash(__('Ingrese correctamente la contraseña nueva.', true));
                }
            }
            else {
                $this->Session->setFlash(__('No coincide contraseña anterior.', true));
            }
//            if ($this->User->save($this->data)) {
//                // Verificar si sus permisos de grupo han cambiado
//                $this->Session->setFlash(__('La contraseña se ha cambiado correctamente', true));
//                $this->redirect(array('action' => 'index'));
//            } else {
//                $this->Session->setFlash(__('Ocurrio un error al guardar la contraseña.', true));
//            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('No existe usuario', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash(__('Usuario eliminado correctamente', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Usuario no se pudo eliminar', true));
        $this->redirect(array('action' => 'index'));
    }

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('login','logout','initDb');
        $this->Auth->autoRedirect = false;
        //$this->Auth->allowedActions = array('*');//cuando no haya ninguno
    }

    function initDb() {
        $group =& $this->User->Group;
        //Allow admins to everything
        $group->id = 1;
        $this->Acl->allow($group, 'controllers');

        $group->id = 2;
        $this->Acl->allow($group, 'controllers');
        $this->Acl->deny($group, 'controllers/Groups');
        $this->Acl->deny($group, 'controllers/Users');
        $this->Acl->allow($group, 'controllers/Users/edit_password');


        //grupo ventas
        $group->id = 3;
        $this->Acl->deny($group, 'controllers');
        $this->Acl->allow($group, 'controllers/Pages');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index_produccion');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index_aprob');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index_orden_inspeccion');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index_cotizacion');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/index_orden_trabajo');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/aprobar');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/view');
        $this->Acl->allow($group, 'controllers/OrdenInspeccions/add');

        $this->Acl->allow($group, 'controllers/Cotizacions/index');
        $this->Acl->allow($group, 'controllers/Cotizacions/view');
        $this->Acl->allow($group, 'controllers/Cotizacions/add');

        $this->Acl->allow($group, 'controllers/OrdenTrabajos/index');
        $this->Acl->allow($group, 'controllers/OrdenTrabajos/view');
        $this->Acl->allow($group, 'controllers/OrdenTrabajos/add');

        $this->Acl->allow($group, 'controllers/Users/edit_password');

        echo "all done";
        exit;
    }

}
?>